import SandboxJS from '@nyariv/sandboxjs';

export class Sandbox {
    async run(script: string, context: any = {}): Promise<any> {
        try {
            // 创建日期工具对象
            const dateTools = {
                parse: (dateStr: string) => {
                    if (!dateStr) return null;
                    
                    // 处理 YYYY-MM-DD 格式
                    const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateStr);
                    if (!match) return null;
                    
                    const [_, year, month, day] = match;
                    return {
                        year: parseInt(year),
                        month: parseInt(month),
                        day: parseInt(day),
                        // 计算年龄
                        getAge: () => {
                            const now = new Date();
                            let age = now.getFullYear() - parseInt(year);
                            const m = now.getMonth() + 1 - parseInt(month);
                            if (m < 0 || (m === 0 && now.getDate() < parseInt(day))) {
                                age--;
                            }
                            return age;
                        },
                        // 格式化日期
                        format: () => `${year}年${month}月${day}日`,
                        // 获取时间戳
                        getTime: () => Date.parse(`${year}-${month}-${day}`)
                    };
                },
                timestampToDate: (timestamp: number|string) => {
                    const date = new Date(Number(timestamp) * 1000); // 将秒转换为毫秒
                    const year = date.getFullYear();
                    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始
                    const day = String(date.getDate()).padStart(2, '0');
                    return `${year}-${month}-${day}`; // 返回格式化的日期字符串
                }
            };

            const sandbox = new SandboxJS({
                globals: {
                    ...SandboxJS.SAFE_GLOBALS,
                    console: console,
                    dateTools
                }
            });

            const exec = sandbox.compile(script);
            return exec({ ...context, dateTools }).run();
        } catch (error) {
            throw error;
        }
    }
} 